import {
  SET_ORDER_MOVE_OPS_FORM,
  SET_ORDER_MOVE_ORDER_LIST,
  UPDATE_ORDER_MOVE_OPS_FORM_QTY,
} from "./action-types";

const initialState = {
  orderList: [],
  orderListOffset: 0,

  opsFormData: null,
};

const handleOrderList = (state, payload) => {
  let { items, offset } = payload;
  if (items.length === 0 && offset === 0) {
    return { ...state, orderList: [], orderListOffset: 0 };
  } else {
    return {
      ...state,
      orderList: state.orderList.concat(items),
      orderListOffset: offset
    };
  }
};

const handleUpdateQty = (state, payload) => {
  let { id, qty } = payload;
  const idx = state.opsFormData.items.findIndex((item) => item.id === id);
  if (idx !== -1) {
    const updateItems = [...state.opsFormData.items];
    updateItems[idx] = {
      ...updateItems[idx],
      qty,
    };

    return {
      ...state,
      opsFormData: { ...state.opsFormData, items: updateItems },
    };
  }
  return state;
};

const data = (state = initialState, action) => {
  switch (action.type) {
    case SET_ORDER_MOVE_ORDER_LIST:
      return handleOrderList(state, action.payload);
    case SET_ORDER_MOVE_OPS_FORM:
      return { ...state, opsFormData: action.payload };
    case UPDATE_ORDER_MOVE_OPS_FORM_QTY:
      return handleUpdateQty(state, action.payload);
    default:
      return state;
  }
};

export default data;
